import re

from fastapi import APIRouter, Request
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.mdeprecated import retry_func_async
from re_common.baselibrary.utils.core.mlamada import bools_string
from re_common.baselibrary.utils.core.requests_core import MsgCode

from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo
from apps.crawler_platform.policy_platform.policy_etl_local import PolicyEtlLocal
from apps.crawler_platform.policy_platform.policy_list import PolcyListDownStep
from apps.crawler_platform.policy_platform.policy_article import PolicyArticleDownStep
from apps.crawler_platform.core_platform.g_model import InputPlatformModel, PolicyListMode, PolicyArticleMode, \
    PolicyUrlConn
from apps.crawler_platform.util.proxyhelper import ProxyHelper
from apps.crawler_platform.util.requestapihelper import RequestApiHelper
from apps.core.return_info import ReturnInfo, FAILED, SUCCESS

router = APIRouter(route_class=ContextIncludedRoute)


@router.post("/policy/list")
async def policy_list(request: Request, input: InputPlatformModel[PolicyListMode]):
    return_info = ReturnInfo()
    down = PolcyListDownStep(request, input)
    bools, err_info = await down.my_task()
    step_info = down.step_info
    return_info.status = bools_string(bools)
    if bools:
        return_info.msg_code = MsgCode.SUCCESS_CODE
        return_info.msg = step_info
        return_info.data = ""
    else:
        return_info.msg_code = 400
        return_info.msg = step_info
        return_info.data = {"err_info": err_info}
    return return_info.todict()


@router.post("/policy/article")
async def policy_article(request: Request, input: InputPlatformModel[PolicyArticleMode]):
    return_info = ReturnInfo()
    down = PolicyArticleDownStep(request, input)
    bools, err_info = await down.my_task()
    step_info = down.step_info
    return_info.status = bools_string(bools)
    if bools:
        return_info.msg_code = MsgCode.SUCCESS_CODE
        return_info.msg = step_info
        return_info.data = ""
    else:
        return_info.msg_code = 400
        return_info.msg = step_info
        return_info.data = {"err_info": err_info}
    return return_info.todict()


@router.post("/policy/etl/local")
async def journal_etl_local(request: Request, input: InputPlatformModel[PolicyArticleMode]):
    """
    期刊本地etl
    :return:
    """
    return_info = ReturnInfo()
    down = PolicyEtlLocal(request, input)
    bools, err_info = await down.my_task()
    step_info = down.step_info
    return_info.status = bools_string(bools)
    if bools:
        return_info.msg_code = MsgCode.SUCCESS_CODE
        return_info.msg = step_info
        return_info.data = ""
    else:
        return_info.msg_code = 400
        return_info.msg = step_info
        return_info.data = {"err_info": err_info}
    return return_info.todict()


@retry_func_async(retry_times=3, sleep_time=1)
async def down_url_conn(url):
    bools, proxies = await ProxyHelper.get_proxy_policy_url_conn()
    if bools:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
        }

        rrq = RequestApiHelper.get_rrq()
        kwargs = {
            "rrq": rrq,
            "header": headers,
            "url": url,
            "timeout": 30,
            "proxy": proxies,
            "moths": MRequest.GET,
            "middler_list": [],
            "allow_redirects": True
        }
        boolsg, dicts = await RequestApiHelper.etl_remote_meta(**kwargs)
        if boolsg:
            if dicts["code"] not in [200, 201, 202, 203]:
                return False, dicts
            else:
                return True, dicts
        else:
            return False, dicts
    else:
        return bools, ""


@router.post("/policy/url_conn")
async def get_url_conn(input: InputPlatformModel[PolicyUrlConn]):
    """
        用于政策测试url有效性
    """
    return_info = ReturnInfo()
    # bools, proxies = await ProxyHelper.get_proxy_policy_url_conn()
    url = input.data.url
    bools, info = await down_url_conn(url)
    if bools:
        return_info.status = SUCCESS
        return_info.msg_code = MsgCode.SUCCESS_CODE
        return_info.msg = "测试连接成功, url存活"
        return_info.data = ""
        return return_info.todict()
    else:
        return_info.status = FAILED
        return_info.msg_code = 303
        return_info.msg = "测试连接失败, url不存活"
        return_info.data = ""
        return return_info.todict()
